import JsonSeriable from "../base/JsonSeriable"
import {seriUniCode} from "../base/jsonSeriableConstants"
import classLoader from "./classLoader"
function jsonSeriObj(obj){
	let isArray = Array.isArray(obj);
	if(isArray){
		// 数组
		let arr = [];
		for(let aitem of obj){
			arr.push(jsonSeriObj(aitem));
		}
		return arr;
	}else{
		// 非数组
		if(obj instanceof JsonSeriable){
			return obj.toSeriObj();
		}else{
			if(typeof(obj) == "object"){
				let ret ={};
				for(let k in obj){
					ret[k] = jsonSeriObj(obj[k]);
				}
				return ret;
			}else{
				return obj;
			}
			
		}
	}
	
}

function seriObj(objEnt){
	
	if(Array.isArray(objEnt)){
		// 数组：
		let arr = [];
		for(let aitem of objEnt){
			arr.push(seriObj(aitem));
		}
		return arr;
	}
	
	if((!objEnt) || typeof(objEnt) != "object"){
		return objEnt;
	}
	
	if(objEnt._seriUniCode != seriUniCode){
		let robj = {};
		for(let k in objEnt){
			robj[k] = seriObj(objEnt[k])
		}
		return robj;
	}
	
	let obj = seriObj(objEnt.obj);
	
	let type = seriObj(objEnt.type);
	
	// if(type && typeof(type) =="object" && type._seriUniCode == seriUniCode){
	// 	console.log("seriObj type object ",type);
	// 	type = seriObj(type);
	// }
	if(type && objEnt._seriUniCode == seriUniCode){
		let cls = null;
		let clsPage = null;
		if(typeof(type) == "string"){
			cls = type;
		}else{
			cls = type.type;
			clsPage = type.page;
		}
		let cs = classLoader.getClassCreator(cls,clsPage);
		if(!cs){
			throw "type 对应class creator 未找到："+clsPage+"."+cls;
		}
		let ncs = cs();
		if(ncs.seri){
			ncs.seri(obj)
		}else{
			throw "type 对应class seri 方法未扎到";
		}
		return ncs;
	}else{
		if(!obj){
			return obj;
		}
		let robj = {};
		for(let k in obj){
			robj[k] = seriObj(obj[k])
		}
		return robj;
		
	}
	
	
}


export default {
	
	
	toSeriStr(obj){
		return JSON.stringify(jsonSeriObj(obj));
	},
	jsonSeriObj,
	seri(str){
		let obj = JSON.parse(str);
		return seriObj(obj)
	}
	
}